package com.seeyon.apps.ext.ObxMsgPush.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.cip.binding.manager.ThirdpartyUserMapperManager;
import com.seeyon.apps.cip.manager.RegisterManager;
import com.seeyon.apps.cip.po.RegisterPO;
import com.seeyon.apps.weixin.util.WeixinUtil;
import com.seeyon.client.CTPRestClient;
import com.seeyon.client.CTPServiceClientManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.usermessage.pipeline.Message;
import com.seeyon.ctp.login.online.OnlineRecorder;
import com.seeyon.ctp.login.online.OnlineUser;
import com.seeyon.ctp.organization.OrgConstants;
import com.seeyon.ctp.util.Datetimes;
import com.seeyon.ctp.util.Strings;


public class MyUtils {
    private static final Logger log = Logger.getLogger(MyUtils.class);
    private static final String TOKENURH = AppContext.getSystemProperty("auth.tokenurl");//OA tokenurl
    private static final String EID = AppContext.getSystemProperty("auth.eid");//云之家 团队EID
    private static final String APPID = AppContext.getSystemProperty("auth.appid");//云之家 appid
    private static final String APPSECRET = AppContext.getSystemProperty("auth.appsecret");//云之家 App Secret
    private static final String SIGNKEY = AppContext.getSystemProperty("auth.signkey");//云之家 Sign Key
    private static final String TXLMY = AppContext.getSystemProperty("auth.txlmy");//云之家 通讯录同步可编辑密钥
    private static final String OAAPPCODE = AppContext.getSystemProperty("auth.oaappcode");//OA应用编号
    private static ThirdpartyUserMapperManager thirdpartyUserMapperManager = (ThirdpartyUserMapperManager) AppContext.getBean("thirdpartyUserMapperManager");
    private static RegisterManager registerManager = (RegisterManager) AppContext.getBean("registerManager");


    public static ThirdpartyUserMapperManager getThirdpartyUserMapperManager() {
        return thirdpartyUserMapperManager;
    }

    public static void setThirdpartyUserMapperManager(ThirdpartyUserMapperManager thirdpartyUserMapperManager) {
        MyUtils.thirdpartyUserMapperManager = thirdpartyUserMapperManager;
    }

    public static RegisterManager getRegisterManager() {
        return registerManager;
    }

    public static void setRegisterManager(RegisterManager registerManager) {
        MyUtils.registerManager = registerManager;
    }

    /**
     * Base加密
     *
     * @param s
     * @return
     */

    public static String getBASE64(String s) {
        byte[] bytes = s.getBytes();
        //Base64 加密
        String encoded = Base64.getEncoder().encodeToString(bytes);
        log.info("Base 64 加密后：" + encoded);
        return encoded;
    }

    /**
     * Base解密
     *
     * @param s
     * @return
     */
    public static String getFromBASE64(String s) {
        //Base64 解密
        byte[] decoded = Base64.getDecoder().decode(s);
        String decodeStr = new String(decoded);
        log.info("Base 64 解密后：" + decodeStr);
        return decodeStr;
    }


    public static String getMessage(Message message, String messageType) throws BusinessException {
        int category = message.getCategory();
        String linkType = message.getLinkType();
        String remoteUrl = message.getRemoteURL();
        String pcUrl = "";
        String content = message.getContent();
        Long memberId = message.getReceiverMember().getId();
        RegisterPO register = registerManager.getRegisterIdByCode(OAAPPCODE);
        String openId = thirdpartyUserMapperManager.findThirdUserID(register.getId(), memberId);
        String loginNane = message.getReceiverMember().getLoginName();
        String base64 = getBASE64(loginNane);
        String ticket = "111222" + base64;
        Long id = message.getReferenceId();
        if ((id != null) && (id.longValue() == -1L) && (message.getLinkParams() != null)
                && (message.getLinkParams().length > 0)) {
            id = Long.valueOf(NumberUtils.toLong(message.getLinkParams()[0], -1L));
        }
        if (("link".equals(messageType)) && (Strings.isNotBlank(linkType))) {
            if (category == ApplicationCategoryEnum.collaboration.key()) {
                String path = "";
                String pcpath = "";
                if (("message.link.col.supervise".equals(linkType)) || ("message.link.col.traceRecord".equals(linkType))
                        || ("message.link.formtrigger.msg.flow".equals(linkType))
                        || ("message.link.formtrigger.msg.unflow".equals(linkType))
                        || ("message.link.formtrigger.cap4.msg.unflow".equals(linkType))) {
                    content = content + " 请登录内部协同系统进行处理，谢谢！";
                    remoteUrl = "";
                } else {
                    path = "/seeyon/m3/apps/v5/collaboration/html/details/summary.html?affairId=" + id
                            + "&openFrom=listPending&summaryId=-1&proxyId=0";
                    pcpath = "/seeyon/collaboration/collaboration.do?method=summary&openFrom=listDone&affairId=" + id;
                    pcUrl = pcpath;
                    remoteUrl = path;
                }
            } else if ((category == ApplicationCategoryEnum.edoc.key())
                    || (category == ApplicationCategoryEnum.edocSend.key())
                    || (category == ApplicationCategoryEnum.edocRec.key())
                    || (category == ApplicationCategoryEnum.edocSign.key())
                    || (category == ApplicationCategoryEnum.exSend.key())
                    || (category == ApplicationCategoryEnum.exSign.key())
                    || (category == ApplicationCategoryEnum.edocRegister.key())
                    || (category == ApplicationCategoryEnum.edocRecDistribute.key())
                    || (category == ApplicationCategoryEnum.exchange.key())) {
                String path = "";
                String pcpath = "";
                if (("message.link.edoc.supervise.detail".equals(linkType))
                        || ("message.link.edoc.supervise.main".equals(linkType))
                        || ("message.link.exchange.distribute".equals(linkType))
                        || ("message.link.exchange.receive".equals(linkType))
                        || ("message.link.exchange.receive.hasten".equals(linkType))
                        || ("message.link.exchange.register.govpending".equals(linkType))
                        || ("message.link.exchange.register.pending".equals(linkType))
                        || ("message.link.exchange.register.receive".equals(linkType))
                        || ("message.link.exchange.registered".equals(linkType))
                        || ("message.link.exchange.send".equals(linkType))
                        || ("message.link.exchange.sent".equals(linkType))
                        || ("message.link.edoc.traceRecord".equals(linkType))) {
                    content = content + " 请登录内部协同系统进行处理，谢谢！";
                    remoteUrl = "";
                } else {
                    id = Long.valueOf(message.getLinkParams()[0]);
                    path = "/seeyon/m3/apps/v5/edoc/html/edocSummary.html?affairId=" + id
                            + "&openFrom=listPending&summaryId=-1&proxyId=0";
                    remoteUrl = path;
                    pcpath = "/seeyon/govdoc/govdoc.do?method=summary&openFrom=listSent&affairId=" + id;
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.meeting.key()) {
                String path = "";
                String pcpath = "";
                if (("message.link.mt.room_perm".equals(linkType))
                        || ("message.link.office.meetingroom".equals(linkType))) {
                    content = content + " 请登录内部协同系统进行处理，谢谢！";
                    remoteUrl = "";
                } else if (("message.link.mt.summary".equals(linkType))
                        || ("message.link.mt.summary_send".equals(linkType))
                        || ("message.link.mt.send.scope".equals(linkType))) {
                    path = "/seeyon/m3/apps/v5/meeting/html/meetingSummary.html?meetingSummaryId=" + id
                            + "&openFrom=message&affairId=-1&proxyId=0&proxy=false";
                    remoteUrl = path;
                    pcUrl = pcpath;
                } else {
                    path = "/seeyon/m3/apps/v5/meeting/html/meetingDetail.html?meetingId=" + id
                            + "&openFrom=pending&affairId=-1&proxyId=0&proxy=false";
                    remoteUrl = path;
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.news.key()) {
                String path = "/seeyon/m3/apps/v5/news/html/newsView.html?newsId=" + id + "&comeFrom=0";
                String pcpath = "/seeyon/newsData.do?method=newsView&from=message&newsId=" + id;
                if ("message.link.news.writedetail".equals(linkType)) {
                    content = content + " 请登录内部协同系统进行处理，谢谢！";
                    remoteUrl = "";
                    pcUrl = "";
                } else {
                    remoteUrl = path;
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.bulletin.key()) {
                String path = "/seeyon/m3/apps/v5/bulletin/html/bulView.html?bulId=" + id + "&comeFrom=0";
                String pcpath = "/seeyon/bulData.do?method=bulView&from=message&bulId=" + id;
                if ("message.link.bul.writedetail".equals(linkType)) {
                    content = content + " 请登录内部协同系统进行处理，谢谢！";
                    remoteUrl = "";
                    pcUrl = "";
                } else {
                    remoteUrl = path;
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.bbs.key()) {
                String path = "/seeyon/m3/apps/v5/bbs/html/bbsView.html?bbsId=" + id + "&from=message";
                remoteUrl = path;
                String pcpath = "/seeyon/bbs.do?method=bbsView&from=message&articleId=" + id;
                pcUrl = pcpath;
            } else if (category == ApplicationCategoryEnum.inquiry.key()) {
                String path = "";
                String pcpath = "";
                if (("message.link.inq.alreadyauditing.pass".equals(linkType))
                        || ("message.link.inq.alreadyauditing.nopass".equals(linkType))) {
                    content = content + " 请登录内部协同系统进行处理，谢谢！";
                    remoteUrl = "";
                    pcUrl = "";
                } else if ("message.link.inq.auditing".equals(linkType)) {
                    path = "/seeyon/m3/apps/v5/inquiry/html/inquiryView.html?inquiryId=" + id + "&comeFrom=2"
                            + "&affairState=4";
                    remoteUrl = path;
                    pcpath = "/seeyon/inquiryData.do?method=inquiryView&from=message&isAuth=true&inquiryId=" + id;
                    pcUrl = pcpath;
                } else {
                    path = "/seeyon/m3/apps/v5/inquiry/html/inquiryView.html?inquiryId=" + id + "&comeFrom=0";
                    remoteUrl = path;
                    pcpath = "/seeyon/inquiryData.do?method=inquiryView&from=message&inquiryId=" + id;
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.show.key()) {
                String showbarId = message.getLinkParams()[0];
                StringBuilder path = new StringBuilder("/seeyon/m3/apps/v5/show/html/showbarDetail.html?id=");
                path.append(showbarId);
                if ("message.link.show.showReply".equals(linkType)) {
                    content = content.replaceAll("\"", "");

                    path.append("&showpostId=").append(message.getLinkParams()[1]);
                    path.append("&commentId=").append(message.getLinkParams()[2]);
                    path.append("&from=").append(message.getLinkParams()[3]);
                } else if ("message.link.show.newshowbar".equals(linkType)) {
                    path.append("&from=").append(message.getLinkParams()[1]);
                } else if (("message.link.show.showpost.settop".equals(linkType))
                        || ("message.link.show.showPraise".equals(linkType))) {
                    path.append("&showpostId=").append(message.getLinkParams()[1]);
                    path.append("&from=").append(message.getLinkParams()[2]);
                }
                path.append("&openType=").append("wechat");
                remoteUrl = path.toString();
            } else if (category == ApplicationCategoryEnum.attendance.key()) {
                String path = "";
                String pcpath = "";
                if ("message.link.attendance.view".equals(linkType)) {
                    path = "/seeyon/m3/apps/v5/attendance/html/attendanceIndex.html?from=message";
                    pcpath = "/seeyon/attendance/attendance.do?method=intoMyAttendance&from=msgRemind";
                } else {
                    path = "/seeyon/m3/apps/v5/attendance/html/attendanceDetail.html?attendanceId=" + id;
                    pcpath = "/seeyon/attendance/attendance.do?method=intoMyAttendance&from=msgAt&target=at&attendanceId=" + id;
                }
                remoteUrl = path;
                pcUrl = pcpath;
            } else if (category == ApplicationCategoryEnum.taskManage.key()) {
                StringBuilder path = new StringBuilder("/seeyon/m3/apps/v5/taskmanage/html/");
                if ("message.link.taskmanage.viewfeedback".equals(linkType)) {
                    path.append("taskFeedbackList.html?openType=wechat&taskId=").append(message.getLinkParams()[0]);
                } else if ("message.link.taskmanage.status".equals(linkType)) {
                    String[] linkParams = message.getLinkParams();
                    path.append("task_index.html?openType=wechat&listType=" + linkParams[0] + "&status=overdue");
                } else {
                    path.append("taskEditor.html?openType=wechat&taskId=").append(message.getLinkParams()[0]);
                }
                remoteUrl = path.toString();
            } else if (category == ApplicationCategoryEnum.calendar.key()) {
                StringBuilder path = new StringBuilder("/seeyon/m3/apps/v5/calendar/html/newCalEvent.html?");
                path.append("id=").append(message.getLinkParams()[0]);
                remoteUrl = path.toString();
            } else if (category == ApplicationCategoryEnum.office.key()) {
                Long affairId = Long.valueOf(-1L);
                if ((message.getLinkParams() != null) && (message.getLinkParams().length > 0)) {
                    affairId = Long.valueOf(NumberUtils.toLong(message.getLinkParams()[0], -1L));
                }
                String path = "/seeyon/m3/apps/v5/office/html/";
                if ("message.link.office.autoN.audit".equals(linkType)) {
                    path = path + "audit_auto.html?affairId=" + affairId;
                    remoteUrl = path;
                    String pcpath = "/seeyon/office/autoUse.do?method=autoAuditEdit&operate=audit&affairId=" + affairId;
                    pcUrl = pcpath;
                } else if ("message.link.office.stockN.audit".equals(linkType)) {
                    path = path + "audit_stock.html?affairId=" + affairId;
                    remoteUrl = path;
                    String pcpath = "/seeyon/office/stockUse.do?method=stockAuditEdit&operate=audit&affairId" + affairId;
                    pcUrl = pcpath;
                } else if ("message.link.office.assetN.audit".equals(linkType)) {
                    path = path + "audit_asset.html?affairId=" + affairId;
                    remoteUrl = path;
                    String pcpath = "/seeyon/office/assetUse.do?method=assetAuditEdit&operate=audit&affairId=" + affairId;
                    pcUrl = pcpath;
                } else if ("message.link.office.bookN.audit".equals(linkType)) {
                    path = path + "audit_book.html?applyId=" + id;
                    remoteUrl = path;
                    String pcpath = "/seeyon/office/bookUse.do?method=bookAuditDetail&bookApplyId=" + affairId;
                    pcUrl = pcpath;
                } else {
                    content = content + " 请登录内部协同系统进行处理，谢谢！";
                    remoteUrl = "";
                }
            } else if (category > 2000) {
                if ((message.getLinkParams() != null) && (message.getLinkParams().length > 0)) {
                    String thirdId = message.getLinkParams()[0];
                    String registerCode = message.getLinkParams()[2];
                    if (StringUtils.isBlank(registerCode)) {
                        remoteUrl = "";
                    } else if (registerCode.startsWith("http")) {
                        remoteUrl = registerCode;
                        if (remoteUrl.contains("?")) {
                            remoteUrl = remoteUrl + "&weixinMessage=true";
                        } else {
                            remoteUrl = remoteUrl + "?weixinMessage=true";
                        }
                    } else {
                        StringBuilder sb = new StringBuilder(
                                "/seeyon/m3/apps/v5/portal/html/cipWeixinMessage.html?thirdpartyMessageId=");
                        sb.append(thirdId);
                        sb.append("&registerCode=");
                        sb.append(registerCode);
                        remoteUrl = sb.toString();
                    }
                } else {
                    remoteUrl = "";
                }
            } else if (category == ApplicationCategoryEnum.ai.key()) {
                String path = "";
                String pcpath = "";
                if ("message.link.col.pending".equals(linkType)) {
                    path = "/seeyon/m3/apps/v5/collaboration/html/details/summary.html?affairId=" + id
                            + "&openFrom=listPending&summaryId=-1&proxyId=0";
                    remoteUrl = path;
                    pcpath = "/seeyon/collaboration/collaboration.do?method=summary&openFrom=listPending&affairId=" + id;
                    pcUrl = pcpath;
                }
            }
        } else {
            remoteUrl = "";
        }
        Long receiverId = message.getReceiverMember().getId();
        Long senderid = Long.valueOf(message.getSenderMemberId());
        log.info("senderid:" + senderid);
        String senderId = thirdpartyUserMapperManager.findThirdUserID(register.getId(), senderid);
        log.info("senderId:" + senderId);
        StringBuilder messagePo = new StringBuilder();
        messagePo.append("{");
        messagePo.append("D:'" + Datetimes.formatDatetime(message.getCreateDate()) + "'");
        messagePo.append(",S:'" + senderId + "'");
        messagePo.append(",R:'" + receiverId + "'");
        messagePo.append(",C:'" + Strings.escapeJavascript(content) + "'");
        messagePo.append(",U:'" + remoteUrl + "'");
        messagePo.append(",M:'" + category + "'");
        messagePo.append(",L:'" + linkType + "'");
        messagePo.append(",I:'" + WeixinUtil.getOaUrl() + "'");
        messagePo.append(",T:'" + ticket + "'");
        messagePo.append(",O:'" + openId + "'");
        messagePo.append(",P:'" + pcUrl + "'");
        messagePo.append("}");
        return messagePo.toString();
    }


    public static String getMessage(int category, String linkType, String id, String id1) throws BusinessException {
        String pcUrl = "";
        if (Strings.isNotBlank(linkType)) {
            if (category == ApplicationCategoryEnum.collaboration.key()) {
                String pcpath = "";
                if (("message.link.col.supervise".equals(linkType)) || ("message.link.col.traceRecord".equals(linkType))
                        || ("message.link.formtrigger.msg.flow".equals(linkType))
                        || ("message.link.formtrigger.msg.unflow".equals(linkType))
                        || ("message.link.formtrigger.cap4.msg.unflow".equals(linkType))) {
                    pcUrl = "";
                } else {
                    pcpath = "/seeyon/collaboration/collaboration.do?method=summary&openFrom=listPending&affairId=" + id;
                    pcUrl = pcpath;
                }
            } else if ((category == ApplicationCategoryEnum.edoc.key())
                    || (category == ApplicationCategoryEnum.edocSend.key())
                    || (category == ApplicationCategoryEnum.edocRec.key())
                    || (category == ApplicationCategoryEnum.edocSign.key())
                    || (category == ApplicationCategoryEnum.exSend.key())
                    || (category == ApplicationCategoryEnum.exSign.key())
                    || (category == ApplicationCategoryEnum.edocRegister.key())
                    || (category == ApplicationCategoryEnum.edocRecDistribute.key())
                    || (category == ApplicationCategoryEnum.exchange.key())) {

                String pcpath = "";
                if (("message.link.edoc.supervise.detail".equals(linkType))
                        || ("message.link.edoc.supervise.main".equals(linkType))
                        || ("message.link.exchange.distribute".equals(linkType))
                        || ("message.link.exchange.receive".equals(linkType))
                        || ("message.link.exchange.receive.hasten".equals(linkType))
                        || ("message.link.exchange.register.govpending".equals(linkType))
                        || ("message.link.exchange.register.pending".equals(linkType))
                        || ("message.link.exchange.register.receive".equals(linkType))
                        || ("message.link.exchange.registered".equals(linkType))
                        || ("message.link.exchange.send".equals(linkType))
                        || ("message.link.exchange.sent".equals(linkType))
                        || ("message.link.edoc.traceRecord".equals(linkType))) {
                    pcUrl = "";
                } else {
                    id = id1;
                    pcpath = "/seeyon/govdoc/govdoc.do?method=summary&openFrom=listSent&affairId=" + id;
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.meeting.key()) {
                String pcpath = "/seeyon/mtMeeting.do?method=myDetailFrame&id=" + id;
                pcUrl = pcpath;
            } else if (category == ApplicationCategoryEnum.news.key()) {
                String pcpath = "/seeyon/newsData.do?method=newsView&from=message&newsId=" + id;
                if ("message.link.news.writedetail".equals(linkType)) {
                    pcUrl = "";
                } else {
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.bulletin.key()) {
                String pcpath = "/seeyon/bulData.do?method=bulView&from=message&bulId=" + id;
                if ("message.link.bul.writedetail".equals(linkType)) {
                    pcUrl = "";
                } else {
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.bbs.key()) {
                String pcpath = "/seeyon/bbs.do?method=bbsView&from=message&articleId=" + id;
                pcUrl = pcpath;
            } else if (category == ApplicationCategoryEnum.inquiry.key()) {
                String pcpath = "";
                if (("message.link.inq.alreadyauditing.pass".equals(linkType))
                        || ("message.link.inq.alreadyauditing.nopass".equals(linkType))) {
                    pcUrl = "";
                } else if ("message.link.inq.auditing".equals(linkType)) {
                    pcpath = "/seeyon/inquiryData.do?method=inquiryView&from=message&isAuth=true&inquiryId=" + id;
                    pcUrl = pcpath;
                } else {
                    pcpath = "/seeyon/inquiryData.do?method=inquiryView&from=message&inquiryId=" + id;
                    pcUrl = pcpath;
                }
            } else if (category == ApplicationCategoryEnum.show.key()) {
                pcUrl = "/seeyon/show/show.do?method=showbar&showbarId=" + id1;
            } else if (category == ApplicationCategoryEnum.attendance.key()) {
                String pcpath = "";
                if ("message.link.attendance.view".equals(linkType)) {
                    pcpath = "/seeyon/attendance/attendance.do?method=intoMyAttendance&from=msgRemind";
                } else {
                    pcpath = "/seeyon/attendance/attendance.do?method=intoMyAttendance&from=msgAt&target=at&attendanceId=" + id;
                }
                pcUrl = pcpath;
            } else if (category == ApplicationCategoryEnum.taskManage.key()) {
                pcUrl = "";
            } else if (category == ApplicationCategoryEnum.calendar.key()) {
                pcUrl = "";
            } else if (category == ApplicationCategoryEnum.office.key()) {
                Long affairId = Long.valueOf(-1L);
                if (Strings.isNotBlank(id1)) {
                    affairId = Long.valueOf(NumberUtils.toLong(id1, -1L));
                }
                if ("message.link.office.autoN.audit".equals(linkType)) {
                    String pcpath = "/seeyon/office/autoUse.do?method=autoAuditEdit&operate=audit&affairId=" + affairId;
                    pcUrl = pcpath;
                } else if ("message.link.office.stockN.audit".equals(linkType)) {
                    String pcpath = "/seeyon/office/stockUse.do?method=stockAuditEdit&operate=audit&affairId" + affairId;
                    pcUrl = pcpath;
                } else if ("message.link.office.assetN.audit".equals(linkType)) {
                    String pcpath = "/seeyon/office/assetUse.do?method=assetAuditEdit&operate=audit&affairId=" + affairId;
                    pcUrl = pcpath;
                } else if ("message.link.office.bookN.audit".equals(linkType)) {
                    String pcpath = "/seeyon/office/bookUse.do?method=bookAuditDetail&bookApplyId=" + affairId;
                    pcUrl = pcpath;
                } else {
                    pcUrl = "";
                }
            } else if (category > 2000) {
                pcUrl = "";
            } else if (category == ApplicationCategoryEnum.ai.key()) {
                String pcpath = "";
                if ("message.link.col.pending".equals(linkType)) {
                    pcpath = "/seeyon/collaboration/collaboration.do?method=summary&openFrom=listPending&affairId=" + id;
                    pcUrl = pcpath;
                }
            }
        } else {
            pcUrl = "";
        }
        return pcUrl;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            /*for (String key : map.keySet()) {
                log.info(key + "--->" + map.get(key));
            }*/
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "gb2312"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String gettoken() {
        String s = sendGet(TOKENURH);
        log.info(s);
        try {
            JSONObject obj = JSONObject.parseObject(s);
            String tokenid = obj.getString("id");
            log.info(tokenid);
            return tokenid;
        } catch (Exception e) {
            return s;
        }
    }

    /**
     * 获取accessToken
     *
     * @param type
     * @return
     */
    public static String getAccessToken(String type) {
        log.info("授权类型：" + type);
        String accessToken = null;
        JSONObject jsonObject = new JSONObject();
        switch (type) {
//		case "app":
//			jsonObject.put("appId", "500877063");
//			jsonObject.put("secret", "6Yae6x9PWTp9RBPOMmKB");
//			jsonObject.put("timestamp", new Date().getTime());
//			jsonObject.put("scope", "app");
//			break;
//		case "team":
//			jsonObject.put("appId", "500877063");
//			jsonObject.put("eid", "4889042");
//			jsonObject.put("secret", "6Yae6x9PWTp9RBPOMmKB");
//			jsonObject.put("timestamp", new Date().getTime());
//			jsonObject.put("scope", "team");
//			break;
//		case "resGroupSecret":
//			jsonObject.put("eid", "4889042");
//			jsonObject.put("secret", "jf0L3FjGj6PukRzcZMzsunNaKKDq65uC");
//			jsonObject.put("timestamp", new Date().getTime());
//			jsonObject.put("scope", "resGroupSecret");
//			break;

            case "app":
                jsonObject.put("appId", APPID);
                jsonObject.put("secret", APPSECRET);
                jsonObject.put("timestamp", new Date().getTime());
                jsonObject.put("scope", "app");
                break;
            case "team":
                jsonObject.put("appId", APPID);
                jsonObject.put("eid", EID);
                jsonObject.put("secret", APPSECRET);
                jsonObject.put("timestamp", new Date().getTime());
                jsonObject.put("scope", "team");
                break;
            case "resGroupSecret":
                jsonObject.put("eid", EID);
                jsonObject.put("secret", TXLMY);
                jsonObject.put("timestamp", new Date().getTime());
                jsonObject.put("scope", "resGroupSecret");
                break;
        }
        String url = "https://yunzhijia.com/gateway/oauth2/token/getAccessToken";
        Map<String, Object> header = new HashMap<String, Object>();
        header.put("Content-Type", "application/json");
        log.info("入参：" + jsonObject.toString());
        String sendByHttp = HttpUtil.sendByHttp(url, header, jsonObject.toString());
        log.info("回参：" + JSONObject.parseObject(sendByHttp).toString());
        if (Strings.isNotBlank(sendByHttp)) {
            if (JSONObject.parseObject(sendByHttp).getBoolean("success")) {
                accessToken = JSONObject.parseObject(sendByHttp).getJSONObject("data").getString("accessToken");
            }
        }
        return accessToken;
    }

    /**
     * 获取接口client对象
     *
     * @return
     * @time 2021年8月19日 下午2:29:31
     */
    public static CTPRestClient getClient() {
        String oaIp = AppContext.getSystemProperty("auth.oaip");
        String rest = AppContext.getSystemProperty("auth.restName");
        String restpass = AppContext.getSystemProperty("auth.restPsw");
        // 获取 CTPServiceClientManager对象
        CTPServiceClientManager clientManager = CTPServiceClientManager.getInstance(oaIp);
        // 通过 OA ip 获取 CTPRestClient对象
        CTPRestClient client = clientManager.getRestClient();
        // 绑定rest 用户名和密码
        client.authenticate(rest, restpass);
        // 绑定登录名 (此登录名必须有相关的接口权限)
        client.bindUser(AppContext.getSystemProperty("auth.bindUser"));
        return client;
    }

    /**
     * 获取单位下所有人员
     *
     * @param accountId
     * @return
     */
    public static JSONArray getOrgMembers(String accountId) {
        CTPRestClient client = getClient();
        return client.get("orgMembers/" + accountId, JSONArray.class);
    }

    /**
     * 获取单位下所有部门
     *
     * @param accountId
     * @return
     */
    public static JSONArray getOrgDepartments(String accountId) {
        CTPRestClient client = getClient();
        return client.get("orgDepartments/" + accountId, JSONArray.class);
    }

    /**
     * @param parentPath 父path
     * @param jsonObject
     * @param lastName
     * @return
     */
    public static String children(String parentPath, JSONObject jsonObject, String lastName) {
        if (!jsonObject.getJSONObject(parentPath).isEmpty()) {
            JSONObject jsonObject2 = jsonObject.getJSONObject(parentPath);
            String name = jsonObject2.getString("name");
            lastName = name + "\\" + lastName;
            lastName = children(parentPath.substring(0, parentPath.length() - 4), jsonObject, lastName);
        }
        return lastName;
    }

    private JSONObject SetThirdpartyUser(JSONObject affairData, String registerCode, Long memberId, Long registerId) throws Exception {
        JSONObject setThirdpartyUser = new JSONObject();
        String noneBindingReceiver = affairData.getString("noneBindingReceiver");
        Long thirdUserId = UUID.randomUUID().getMostSignificantBits();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("registerCode", registerCode);
        jsonObject.put("thirdUserId", thirdUserId);
        jsonObject.put("thirdLoginName", noneBindingReceiver);
        jsonObject.put("thirdMobile", noneBindingReceiver);
        CTPRestClient client = getClient();
        log.info("发送参数:" + jsonObject.toString());
        JSONObject resultMap = client.post("thirdpartyUserMapper/binding/singleUser", jsonObject, JSONObject.class);
        log.info("返回结果:" + resultMap.toString());
        setThirdpartyUser.put("thirdUserId", thirdUserId);
        setThirdpartyUser.put("success", resultMap.getBoolean("success"));
        return setThirdpartyUser;
    }

    public static String SetThirdpartyUser(String sendByHttp) {
        JSONArray jsonArray = new JSONArray();
        if (sendByHttp != null) {
            log.info("params:" + JSONObject.parseObject(sendByHttp));
            JSONObject parseObject = JSONObject.parseObject(sendByHttp);
            if (parseObject.getBoolean("success")) {
                JSONArray dataArray = parseObject.getJSONArray("data");
                for (int i = 0; i < dataArray.size(); i++) {
                    if (dataArray.getJSONObject(i).getBoolean("success")) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("registerCode", OAAPPCODE);
                        jsonObject.put("thirdUserId", dataArray.getJSONObject(i).getString("openId"));
                        jsonObject.put("thirdMobile", dataArray.getJSONObject(i).getString("phone"));
                        jsonObject.put("thirdLoginName", dataArray.getJSONObject(i).getString("phone"));
                        jsonArray.add(jsonObject);
                    }
                }
            }
        }
        CTPRestClient client = getClient();
        JSONObject Object = new JSONObject();
        Object.put("userlist", jsonArray);
        log.info("发送参数:" + Object.toString());
        String resultMap = client.post("thirdpartyUserMapper/binding", Object, String.class);
        log.info("返回结果:" + resultMap);
        return resultMap;

    }

    public static String getMessageJson(Message message, String platform) {
        String messageJson = "";
        try {
            boolean isSendMessage = true;
            if (message.getReceiverMember().getExternalType().intValue() != OrgConstants.ExternalType.Inner.ordinal()) {
                isSendMessage = false;
            }
            if (!WeixinUtil.isOnline()) {
                OnlineUser onlineUser = (OnlineUser) OnlineRecorder.getOnlineUser(message.getReceiverMember().getLoginName());
                if (onlineUser != null) {
                    Set<String> loginTypes = onlineUser.getLoginTypes();
                    if ((loginTypes != null) && ((loginTypes.contains(Constants.login_useragent_from.pc.name()))
                            || (loginTypes.contains(Constants.login_useragent_from.iphone.name()))
                            || (loginTypes.contains(Constants.login_useragent_from.androidphone.name()))
                            || (loginTypes.contains(Constants.login_useragent_from.ipad.name()))
                            || (loginTypes.contains(Constants.login_useragent_from.androidpad.name())))) {
                        isSendMessage = false;
                    }
                }
            }
            if (isSendMessage) {
                if ((message.getCategory() == ApplicationCategoryEnum.collaboration.key())
                        || (message.getCategory() == ApplicationCategoryEnum.edoc.key())
                        || (message.getCategory() == ApplicationCategoryEnum.edocSend.key())
                        || (message.getCategory() == ApplicationCategoryEnum.edocRec.key())
                        || (message.getCategory() == ApplicationCategoryEnum.edocSign.key())
                        || (message.getCategory() == ApplicationCategoryEnum.exSend.key())
                        || (message.getCategory() == ApplicationCategoryEnum.exSign.key())
                        || (message.getCategory() == ApplicationCategoryEnum.edocRegister.key())
                        || (message.getCategory() == ApplicationCategoryEnum.edocRecDistribute.key())
                        || (message.getCategory() == ApplicationCategoryEnum.exchange.key())
                        || (message.getCategory() == ApplicationCategoryEnum.news.key())
                        || (message.getCategory() == ApplicationCategoryEnum.bulletin.key())
                        || (message.getCategory() == ApplicationCategoryEnum.bbs.key())
                        || (message.getCategory() == ApplicationCategoryEnum.show.key())
                        || (message.getCategory() == ApplicationCategoryEnum.inquiry.key())
                        || (message.getCategory() == ApplicationCategoryEnum.calendar.key())
                        || (message.getCategory() == ApplicationCategoryEnum.taskManage.key())
                        || (message.getCategory() == ApplicationCategoryEnum.meeting.key())
                        || (message.getCategory() == ApplicationCategoryEnum.attendance.key())
                        || (message.getCategory() == ApplicationCategoryEnum.office.key())
                        || (message.getCategory() == ApplicationCategoryEnum.ai.key())
                        || (message.getCategory() > 2000)) {
                    if (WeixinUtil.isLink()) {
                        messageJson = getMessage(message, "link");
                    } else {
                        messageJson = getMessage(message, "text");
                    }
                } else if ((message.getCategory() == ApplicationCategoryEnum.doc.key())
                        || (message.getCategory() == ApplicationCategoryEnum.plan.key())
                        || (message.getCategory() == ApplicationCategoryEnum.behavioranalysis.key())
                        || (message.getCategory() == ApplicationCategoryEnum.hr.key())) {
                    messageJson = getMessage(message, "text");
                }
            }
        } catch (Exception e) {
            log.error("组装微信消息失败！", e);
        }
        return messageJson;
    }
}
